import datetime

from flask import render_template, session, request, redirect, url_for
from app import create_app
from app.models.tablemodel import Users, Credit

app = create_app()


# 全局404拦截器
@app.errorhandler(404)
def error(e):
    return render_template('error.html')


# 全局500拦截器
@app.errorhandler(500)
def error(e):
    return render_template('error-500.html')


# 全局拦截器
@app.before_request
def authentic():
    pass_list = ['/logout', '/login', '/loginfo', '/reg', '/vcode', '/api/most_recommend', '/login/forgot',
                 '/favicon.ico']
    if request.path.startswith("/static") or request.path.startswith("/upload"):
        # 不让拦截器拦截静态文件
        return
    if request.path in pass_list:
        return
    # if request.path.startswith("/ueditor-plus"):
    #     print('jjj')
    #     return
    if session.get('islogin') is None:
        username = request.cookies.get('username')
        password = request.cookies.get('password')
        if username and password:
            user = Users().find_by_username(username)
            session['islogin'] = 'true'
            session['userid'] = user[0].userid
            session['username'] = user[0].username
            session['nickname'] = user[0].nickname
            session['role'] = user[0].role
            session['avatar'] = user[0].avatar
            session['last_login_date'] = user[0].last_login_date
            if session['last_login_date'] != str(datetime.date.today()):
                Users().update_login_info()
                session['last_login_date'] = str(datetime.date.today())
                Credit().insert_detail('正常登录', 0, 1)
            return
        elif request.path == '/':
            return
        else:
            session['prev_page'] = request.url
            return redirect(url_for('auth.login'))
    else:
        if session['last_login_date'] != str(datetime.date.today()):
            # print(session['last_login_date'], type(session['last_login_date']))
            # print(datetime.date.today(), type(datetime.date.today()))
            Users().update_login_info()
            session['last_login_date'] = str(datetime.date.today())
            Credit().insert_detail('正常登录', 0, 1)
        return


# 定义文章类型函数，供模板页面直接调用，全局函数和template_global区别在于前者可以返回变量，后者只能是函数
@app.context_processor
def gettype():
    types = {
        '1': '工作',
        '2': 'Python开发',
        '3': 'Web前端',
        '4': '典型应用',
    }
    # print(dict(article_type=types))
    return dict(article_type=types)


# 自定义过滤器，实现中文字符当作1，英文0.5进行截断。
@app.template_filter()
def mytruncate(s, length, end='...'):
    count = 0
    new = ""
    for c in s:
        if ord(c) <= 128:
            count += 0.5
        else:
            count += 1
        new += c
        if count > length:
            break
    return new + end


if __name__ == '__main__':
    app.run(debug=True)
